<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Connect to the MySQL database
 * @return \mysqli The database object
 */
function connectToDatabase() {
    return new mysqli("localhost", "rmplanne_andrew", "Pi39RQ", "rmplanne_rmplanner");
}

/**
 * Echo an XML document containing the meal data to the iOS/Android device 
 */
function getMeals() {
    $db = connectToDatabase();
    header("Content-type: text/xml");
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    echo "<data>\n";
    
    $results = $db->query("SELECT * FROM meals 
        JOIN mealtime_meals ON mealtime_meals.meal_id = meals.meal_id
        JOIN mealtimes ON mealtimes.mealtime_id = mealtime_meals.mealtime_id
        WHERE mealtimes.mealtime_date=CURDATE()");
    $db->commit();
    
    echo "<count>$results->num_rows</count>\n";
    while ($row = $results->fetch_assoc()) {
        $name = $row["meal_title"];
        $id = $row["meal_id"];
        $description = $row["meal_description"];
        echo "<meal>\n";
        echo "<id>$id</id>\n";
        echo "<name>$name</name>\n";
        echo "<description>$description</description>\n";
        echo "</meal>\n";
    }
    
    echo "</data>\n";
    $results->free();
    
    $db->close();
}

/**
 * Post a vote to the server, or update one that already exists. Send an acknowledgement.
 */
function postVote($vote, $id)
{
    $db = connectToDatabase();
    $result = $db->query("SELECT * FROM user_votes WHERE user_id='$id'");
    $db->commit();
    $row = $result->fetch_array();
    if ($row[0]) {
        $success = $db->query("UPDATE user_votes SET mealtime_meal_id='$vote' WHERE user_id='$id'");
        $db->commit();
        if ($success)
            echo "Vote updated";
        else
            echo "Error: Vote not updated";
    }
    else {
        $success = $db->query("INSERT INTO user_votes (user_id, mealtime_meals_id) VALUES ($id, $vote)");
        $db->commit();
        if ($success)
            echo "Vote registered. You may change your vote until";
        else
            echo "Error: Vote not registered. Please try again.";
    }
    $db->close();
}

/**
 * Post an order for a late meal to the server 
 */
function postOrder($order, $id) {
    $db = connectToDatabase();
    $success = $db->query("INSERT INTO user_orders (user_id, mealtime_meals_id) 
            VALUES ($id, (SELECT mealtime_meals_id FROM mealtime_meals
            WHERE meal_id=$order))");
    
    $db->commit();
    if ($success)
        echo "Late meal order registered";
    else
        echo "Error: Order not registered. Please try again.";
    $db->close();
}

if ($_SERVER['REQUEST_METHOD'] == 'GET')
    getMeals();
else {
    if ($_POST["type"] == "vote")
        postVote($_POST["mid"], $_POST["uid"]);
    else if ($_POST["type"] == "order")
        postOrder($_POST["mid"], $_POST["uid"]);
}
?>
